/*
 * Created: Author: Aléx Carvalho / Date: Mar 11, 2015
 * 
 * Changed: $Author: ac280593@gmail.com $ / $Date: 2015-06-11 04:31:49 +0000 (Thu, 11 Jun 2015) $
 */
package com.cpm.view.zk;

import com.cpm.Callback;
import com.cpm.ServiceLocator;
import com.cpm.view.CSSClass;
import com.cpm.view.Element;
import com.cpm.view.zk.applications.AbstractApplication;
import java.util.Set;
import org.zkoss.zhtml.Li;
import org.zkoss.zhtml.impl.ContentTag;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.HtmlNativeComponent;
import org.zkoss.zk.ui.event.Events;

public class VerticalMenu implements Element<Component> {

    private final HtmlNativeComponent ul = new HtmlNativeComponent("ul");
    private final HtmlNativeComponent nav = new HtmlNativeComponent("nav");

    private final Set<AbstractApplication> items;

    private Callback<AbstractApplication> callback = null;

    public VerticalMenu() {
        items = ServiceLocator.lookupAll(AbstractApplication.class);

        initComponents();
    }

    @Override
    public Component getElement() {
        return nav;
    }

    public void setCallback(Callback<AbstractApplication> callback) {
        this.callback = callback;
    }

    private void initComponents() {

        nav.setId("vmenunav");
        nav.setDynamicProperty("class", CSSClass.V_MENU_NAV);
        nav.appendChild(ul);

        ul.setDynamicProperty("class", CSSClass.V_MENU);

        nav.setWidgetListener("onBind", "verticalMenu();");

        ul.getChildren().clear();

        items.stream().sorted((a, b) -> a.getPosition().compareTo(b.getPosition())).forEach(item -> {
            ContentTag a = new ContentTag("a");
            a.setDynamicProperty("class", CSSClass.V_MENU_ICON + " " + item.getIcon().getIconClass());
            a.setContent(item.getLabel());

            Li li = new Li();
            li.setWidgetListener("onBind", "controlClick(this);");
            li.setDynamicProperty("class", CSSClass.V_MENU_ITEM);
            li.appendChild(a);
            li.addEventListener(Events.ON_CLICK, e -> {
                if (callback != null) {
                    callback.accept(item);
                }
            });

            ul.appendChild(li);
        });

    }
}
